package com.gokzzz.mq.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gokzzz.mq.config.RabbitMqConfig;
import com.gokzzz.mq.index.ArticleMqIndexMessage;
import com.gokzzz.service.EsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 监听异步消息队列
 * 更新搜索内容
 *
 * @author gokzzz
 * @date 2022-05-22 20:59
 */
@Slf4j
@Component
@RabbitListener(queues = RabbitMqConfig.ES_QUEUE)
@RequiredArgsConstructor
public class HandlerMessage {
    private final ObjectMapper objectMapper;
    private final EsService esService;
    @RabbitHandler
    public void handler(String content) {
        try {
            ArticleMqIndexMessage message = objectMapper.readValue(content, ArticleMqIndexMessage.class);
            switch (message.getType()) {
                case ArticleMqIndexMessage.CREATE:
                case ArticleMqIndexMessage.UPDATE:
                    esService.createOrUpdateIndex(message);
                    break;
                case ArticleMqIndexMessage.REMOVE:
                    esService.removeIndex(message);
                    break;
                default:
                    log.warn("没有找到对应的消息类型，请注意！！！, --->  {}", content);
                    break;
            }
        } catch (IOException e) {
            log.error("这是内容----> {}", content);
            log.error("处理HandlerMessage失败 --> ", e);
        }
    }

}
